package agency.tango.materialintroscreen.parallax;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.StackLayout;
import ohos.app.Context;


import agency.tango.materialintroscreen.AttrString;

/**
 * @ProjectName: material-intro-screen-master
 * @Package: agency.tango.materialintroscreen.parallax
 * @ClassName: ParallaxStackLayout
 * @Description: 可偏移StackLayout 根据容器内各个子控件在水平方向的位置 随着滑动按比例偏移子控件
 * @CreateDate: 2021/4/12 17:12
 * @UpdateDate: 2021/4/12 17:12
 * @UpdateRemark: 暂无
 * @Version: 1.0
 */
public class ParallaxStackLayout extends StackLayout implements Parallaxable {
    public ParallaxStackLayout(Context context) {
        super(context);
    }

    public ParallaxStackLayout(Context context, AttrSet attrs) {
        super(context, attrs);
    }

    @Override
    public ComponentContainer.LayoutConfig createLayoutConfig(Context context, AttrSet attrSet) {
        return new LayoutConfig(context, attrSet);
    }

    @Override
    public void setOffset(float offset) {
        for (int i = getChildCount() - 1; i >= 0; i--) {
            Component child = getComponentAt(i);
            ParallaxStackLayout.LayoutConfig layoutParams = (LayoutConfig) child.getLayoutConfig();
            if (layoutParams.parallaxFactor == 0) {
                continue;
            }

            child.setTranslationX(getWidth() * -offset * layoutParams.parallaxFactor);
        }
    }

    /**
     * 自定义控件参数
     */
    public static class LayoutConfig extends StackLayout.LayoutConfig {
        float parallaxFactor = 0f;

        LayoutConfig(Context context, AttrSet attributeSet) {
            super(context, attributeSet);
            parallaxFactor =
                    attributeSet.getAttr(AttrString.PARALlAX_LAYOUT_FACTOR).isPresent() ?
                            attributeSet.getAttr(AttrString.PARALlAX_LAYOUT_FACTOR).get().getFloatValue()
                            : parallaxFactor;
        }

        LayoutConfig(int width, int height) {
            super(width, height);
        }

        LayoutConfig(int width, int height, int gravity) {
            super(width, height, gravity);
        }

        LayoutConfig(ComponentContainer.LayoutConfig source) {
            super(source);
        }
    }
}